//
//  PersonalInfoViewController.m
//  seer
//
//  Created by Lin Eidan on 14-5-28.
//  Copyright (c) 2014年 haomee. All rights reserved.
//

#import "PersonalInfoViewController.h"
#import "Header.h"
#import "config.h"
#import "CameraAndPhoto.h"
#import "VPImageCropperViewController.h"
#import "UpYun.h"
#import "RegisterViewController.h"
#import <Frontia/Frontia.h>
#import "UIImagePickerController+NonRotating.h"

#define CellIdentifer       @"cellIdentifer"
#define UPYunBase           @"http://haomee.b0.upaiyun.com"

#define AlertViewChangeNameTag      1000

@interface PersonalInfoViewController ()<UIAlertViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,VPImageCropperDelegate>

@property (strong, nonatomic) IBOutlet UIView *navBarView;
@property (strong, nonatomic) IBOutlet UIScrollView *myScrollView;

@property (strong, nonatomic) IBOutlet UIImageView *headPicImageView;
@property (strong, nonatomic) IBOutlet UILabel *userNameLabel;

@property (strong, nonatomic) UICollectionView *headerCollectView;
@property (strong, nonatomic) NSArray *headerArray;
@property (strong, nonatomic) IBOutlet UIView *headerCollectBgView;
@property (assign, nonatomic) int selectedHeaderIndex;
@property (strong, nonatomic) UIImage *justGetInCustomHeaderImage; //防止自定义头像时，只改了昵称，头像没有改，但头像又重新上传和生成。

@property (strong, nonatomic) UICollectionView *campCollectView;
@property (strong, nonatomic) NSArray *campArray;
@property (strong, nonatomic) IBOutlet UIView *campCollectBgView;
@property (assign, nonatomic) int selectedCampIndex;

@property (strong, nonatomic) IBOutlet UIView *bottomView;
@property (strong, nonatomic) IBOutlet UIButton *submitBtn;
@property (strong, nonatomic) IBOutlet UIView *thirdBindBgView;

//phone
@property (strong, nonatomic) IBOutlet UIView *phoneBgView;
@property (strong, nonatomic) IBOutlet UIButton *changePhoneBtn;
@property (strong, nonatomic) IBOutlet UILabel *phoneLabel;

//sina
@property (strong, nonatomic) IBOutlet UIView *sinaBgView;
@property (strong, nonatomic) IBOutlet UILabel *weiboLabel;
@property (strong, nonatomic) IBOutlet UIButton *bindWeiBoBtn;

//qq
@property (strong, nonatomic) IBOutlet UIView *qqBgView;
@property (strong, nonatomic) IBOutlet UILabel *qqLabel;
@property (strong, nonatomic) IBOutlet UIButton *bindQQBtn;




@end

@implementation PersonalInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.selectedHeaderIndex = 0;
        self.selectedCampIndex =0;
        self.firstRegisterToGoTo = NO;
        self.justGetInCustomHeaderImage = nil;
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self drawNavTopContentView:self.navBarView];
    [self initUI];
    // Do any additional setup after loading the view from its nib.
}


-(void)initUI{
    self.bindWeiBoBtn.layer.cornerRadius = 3;
    self.changePhoneBtn.layer.cornerRadius = 3;
    self.bindQQBtn.layer.cornerRadius = 3;
    
    if ([kHandle sharedInstance].isShowTrueView) {
        self.thirdBindBgView.height = 162;
        self.thirdBindBgView.alpha = 1;
    }else{
        self.thirdBindBgView.height = 0;
        self.thirdBindBgView.alpha = 0;
    }
    
    self.bottomView.top = 490;
    [self.myScrollView addSubview:self.bottomView];
    self.thirdBindBgView.top = self.bottomView.bottom;
    [self.myScrollView addSubview:self.thirdBindBgView];
    self.myScrollView.contentHeight = self.thirdBindBgView.bottom;
    
    self.headerCollectView = [self drawCollectionViewWithFrame:self.headerCollectBgView.frame andFlowLayout:[self getFlowLayout]];
    [self registerCellAndHeaderForCollectionView:self.headerCollectView];
    [self.myScrollView addSubview:self.headerCollectView];
    
    self.campCollectView = [self drawCollectionViewWithFrame:self.campCollectBgView.frame andFlowLayout:[self getFlowLayout]];
    [self registerCellAndHeaderForCollectionView:self.campCollectView];
    [self.myScrollView addSubview:self.campCollectView];
    
    self.headPicImageView.layer.cornerRadius = self.headPicImageView.width/2;
    self.headPicImageView.layer.masksToBounds = YES;
    self.headPicImageView.clipsToBounds = YES;
    self.headPicImageView.layer.borderColor = RGB(210, 210, 210).CGColor;
    self.headPicImageView.layer.borderWidth = 2;
    
    UserObj *obj = [UserObj sharedInstance];
    if (obj.username.length == 0) {
        obj.username = DefaultUserName;
    }
    self.userNameLabel.text = obj.username;
    
    if ([obj.headPicSrc rangeOfString:@"http://"].location != NSNotFound && obj.headPicSrc) {  //如果是网络地址，先取。
        [[AFGetData sharedInstance] initSDWebImage:[UserObj sharedInstance].headPicSrc andTrueImageView:self.headPicImageView andPlaceholderImage:nil];
    }else{
        self.headPicImageView.image = [UIImage imageNamed:DefaultUserHeaderPic];
    }
    
    if ([obj.headPicSrc rangeOfString:UPYunBase].location != NSNotFound && obj.headPicSrc) { //如果是自定义的地址，那么headId就为－1，这样self.selectedHeaderIndex才为0。
        obj.headId = @"-1";
    }
    
    [kApp displayWaitViewWithAllMaskView:NO];
    NSString *url = [NSString stringWithFormat:@"%@getHeadAndCamp&pf=2",API_BASE];
    [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        [kApp hideWaitView];
        if (isSuccess) {
            NSDictionary * wholeDict = responseObj;
            self.headerArray = [wholeDict objectForKey:@"head"];
            self.campArray = [wholeDict objectForKey:@"camp"];

            for (int i=0 ; i < self.headerArray.count; i++) {
                NSDictionary *dic = [self.headerArray objectAtIndex:i];
                if ([[dic objectForKey:@"id"] intValue] == [UserObj sharedInstance].headId.intValue) {
                    self.selectedHeaderIndex = i;
                    break;
                }
            }
            
            for (int i=0 ; i < self.campArray.count; i++) {
                NSDictionary *dic = [self.campArray objectAtIndex:i];
                if ([[dic objectForKey:@"id"] intValue] == [UserObj sharedInstance].campId.intValue) {
                    self.selectedCampIndex = i;
                    break;
                }
            }
            
            [self.headerCollectView reloadData];
            [self.campCollectView reloadData];
        }else{
            [[kHandle sharedInstance] showTipsWhenRequestFailedWithView:nil];
            [self performSelector:@selector(goBack:) withObject:nil afterDelay:0.7];
            return;
        }
    }];
    
    
    [self performSelector:@selector(delayToStoreTheCustomHeaderImage) withObject:nil afterDelay:0.3];
    [self initBingUI];
}

-(void)delayToStoreTheCustomHeaderImage{
    //刚进来，存储一下，如果提交的时候，自定义头像没有变，他们还是相等的。
    self.justGetInCustomHeaderImage = self.headPicImageView.image;
    
}

-(void)initBingUI{

    //bangding
    UserObj *obj = [UserObj sharedInstance];
    if (obj.phoneNum) {
        self.phoneLabel.text = obj.phoneNum;
    }
    [self refreshQQBindUI];
    [self refreshSinaBindUI];
}

-(void)refreshSinaBindUI{
    UserObj *obj = [UserObj sharedInstance];
    if (![obj.sinaId isEqualToString:@"0"]) {
        self.weiboLabel.text = obj.sinaNickName;
        self.bindWeiBoBtn.selected = YES;
    }else{
        self.weiboLabel.text = @"";
        self.bindWeiBoBtn.selected = NO;
    }
}

-(void)refreshQQBindUI{
    UserObj *obj = [UserObj sharedInstance];
    if (![obj.qqId isEqualToString:@"0"]) {
        self.qqLabel.text = obj.qqNickName;
        self.bindQQBtn.selected = YES;
    }else{
        self.qqLabel.text = @"";
        self.bindQQBtn.selected = NO;
    }
}

#pragma -mark 绑定和更换手机号
- (IBAction)changePhone:(id)sender {
    UserObj *obj = [UserObj sharedInstance];
    if (obj.phoneNum.length != 11 || obj.accessKey.length == 0 || obj.uid.length == 0) {
        [PopTips tipsAtTop:self.view Msg:NotifyCanNotChangPhone];
        return;
    }
    //更换手机号的流程是：进入注册页面，调用手机注册接口，这个手机没有被注册过，然后给新手机号发验证码，验证通过后，才能开始调用绑定接口，这时候成功，才算成功。
    RegisterViewController *registerVC = [[RegisterViewController alloc] initWithNibName:@"RegisterViewController" bundle:nil];
    registerVC.isFromeChangePhone = YES;
    [self.navigationController pushViewController:registerVC animated:YES];
}

-(void)changePhoneWithPhoneNum:(NSString *)phoneNum{
    UserObj *obj = [UserObj sharedInstance];
    [kApp displayWaitViewWithAllMaskView:NO];
    NSString *url = [NSString stringWithFormat:@"%@changePhone&uid=%@&ak=%@&mobile=%@",API_BASE,obj.uid,obj.accessKey,phoneNum];
    [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        if (isSuccess) {
            [kApp hideWaitView];
            int flag = [[responseObj objectForKey:@"flag"] intValue];
            if (flag == 1) {
                obj.phoneNum = phoneNum;
                if (obj.phoneNum) {
                    self.phoneLabel.text = obj.phoneNum;
                }
                [PopTips tipsAtTop:self.view Msg:NotifyChangePhoneSuccess];
                [obj saveUserToLocal];
            }else{
                [PopTips tipsAtTop:self.view Msg:NotifyChangePhoneFailed];
            }
        }else{
            [[kHandle sharedInstance] showTipsWhenRequestFailedWithView:self.view];
        }
    }];

    
}

- (IBAction)bindWeiBo:(id)sender {
    UIButton *btn = (UIButton *)sender;
    if (btn.selected) {
        [self unbindlingWithType:BindSinaPfIndex andBtn:btn]; // 解绑
    }else{
        [self bindingWithType:BindSinaPfIndex andBtn:btn];
    }
}

- (IBAction)bindQQ:(id)sender {
    UIButton *btn = (UIButton *)sender;
    if (btn.selected) {
        [self unbindlingWithType:BindQQPfIndex andBtn:btn]; // 解绑
    }else{
        [self bindingWithType:BindQQPfIndex andBtn:btn];
    }
}

//绑定
-(void)bindingWithType:(NSString *)type andBtn:(UIButton *)btn{
    btn.enabled = NO;
    UserObj *obj = [UserObj sharedInstance];
    if (obj.phoneNum.length != 11 || obj.accessKey.length == 0 || obj.uid.length == 0) {
        [PopTips tipsAtTop:self.view Msg:NotifyBindFaild];
        return;
    }
    FrontiaAuthorization * authorization = [Frontia getAuthorization];
    
    NSString *platformType = nil;
    if ([type isEqualToString:BindQQPfIndex]) {
        platformType = FRONTIA_SOCIAL_PLATFORM_QQ;
    }else{
        platformType = FRONTIA_SOCIAL_PLATFORM_SINAWEIBO;
    }
    
    FrontiaAuthorizationCancelCallback onCancel = ^(){
        [kApp hideWaitView];
        btn.enabled = YES;
    };
    
    FrontiaAuthorizationFailureCallback onFailure = ^(int errorCode, NSString *errorMessage){
        [kApp hideWaitView];
        btn.enabled = YES;
        [PopTips tipsAtTop:self.view Msg:NotifyThirdAuthorizeFaild];
    };
    
    FrontiaAuthorizationResultCallback onResult = ^(FrontiaUser *result){
        [Frontia setCurrentAccount:result];
        
        NSString *url = [NSString stringWithFormat:@"%@pfLogin",API_BASE];
        NSDictionary *dic = @{@"pf_type": type ,@"pf_id":result.mediaUid,@"ak":[Common md5:[NSString stringWithFormat:@"%@%@",type,result.mediaUid]]};  //验证一下这个第三方账号是否已经绑定了其他手机，没有绑定其他手机才可以。
        [[AFGetData sharedInstance] startPost:url andInfo:dic andDataBodyBlock:^(id<AFMultipartFormData> formData) {
        } andRequestCompletion:^(id responseObj, BOOL isSuccess) {
            [kApp hideWaitView];
            if (isSuccess) {
                int flag = [[responseObj objectForKey:@"flag"] intValue];
                if (1 == flag) {  //可以登录成功，证明已经绑定了其他手机,就不可以绑定这个手机。
                    btn.enabled = YES;
                    [PopTips tipsAtTop:self.view Msg:NotifyThirdAccoutHasBeenUsed];
                }else if (0 == flag){ //需要绑定手机号，证明，这个账号还没被绑定，可以用来绑定。
                    
                    NSString *newURL = [NSString stringWithFormat:@"%@phoneBindpf",API_BASE];
                    NSDictionary *newDic = @{@"pf_type": type,@"pf_id":result.mediaUid,@"ak":obj.accessKey,@"uid":obj.uid,@"pf_nickname":result.accountName};
                    
                    [[AFGetData sharedInstance] startPost:newURL andInfo:newDic andDataBodyBlock:^(id<AFMultipartFormData> formData) {
                        
                    } andRequestCompletion:^(id responseObj, BOOL isSuccess) {
                        btn.enabled = YES;
                        if (isSuccess) {
                            int flag = [[responseObj objectForKey:@"flag"] intValue];
                            if (1 == flag) {
                                if ([type isEqualToString:BindQQPfIndex]) {
                                    obj.qqId = result.mediaUid;
                                    obj.qqNickName = result.accountName;
                                    [self refreshQQBindUI];
                                }else{
                                    obj.sinaId = result.mediaUid;
                                    obj.sinaNickName = result.accountName;
                                    [self refreshSinaBindUI];
                                }
                                [PopTips tipsAtTop:self.view Msg:NotifyThirdBindSuccess];
                                [obj saveUserToLocal];
                            }else if(2 == flag){
                                [PopTips tipsAtTop:self.view Msg:NotifyPhoneHasBind];
                            }else{
                                [PopTips tipsAtTop:self.view Msg:NotifyBindFaild];
                            }
                        }else{
                            [[kHandle sharedInstance] showTipsWhenRequestFailedWithView:self.view];
                        }
                    }];
                }else{  //无效请求。
                    [PopTips tipsAtTop:self.view Msg:NotifyBindFaild];
                    btn.enabled = YES;
                }
            }else{
                btn.enabled = YES;
                [[kHandle sharedInstance] showTipsWhenRequestFailedWithView:self.view];
            }
        }];
        
        
    };
    
    [kApp displayWaitViewWithAllMaskView:NO];
    [authorization authorizeWithPlatform:platformType supportedInterfaceOrientations:UIInterfaceOrientationMaskPortrait isStatusBarHidden:NO cancelListener:onCancel failureListener:onFailure resultListener:onResult];
    
}

//解绑
-(void)unbindlingWithType:(NSString *)type andBtn:(UIButton *)btn{
    btn.enabled = NO;
    UserObj *obj = [UserObj sharedInstance];
    [kApp displayWaitViewWithAllMaskView:NO];
    NSString *url = [NSString stringWithFormat:@"%@phoneReleasePf&uid=%@&ak=%@&pf_type=%@",API_BASE,obj.uid,obj.accessKey,type];
    [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        btn.enabled = YES;
        [kApp hideWaitView];
        if (isSuccess) {
            int flag = [[responseObj objectForKey:@"flag"] intValue];
            if (flag == 1) {
                if ([type isEqualToString:BindQQPfIndex]) {
                    obj.qqId = @"0";
                    obj.qqNickName = @"";
                    [self refreshQQBindUI];
                }else{
                    obj.sinaId = @"0";
                    obj.sinaNickName = @"";
                    [self refreshSinaBindUI];
                }
                [PopTips tipsAtTop:self.view Msg:NotifyThirdUnBindSuccess];
                [obj saveUserToLocal];
            }else{
                [PopTips tipsAtTop:self.view Msg:NotifyThirdUnBindFailed];
            }
        }else{
            [[kHandle sharedInstance] showTipsWhenRequestFailedWithView:self.view];
        }
    }];
}



#pragma -mark xib click

- (IBAction)submit:(id)sender {
    
    if (self.selectedHeaderIndex == 0) {  //自定义头像。
        if (self.headPicImageView.image == self.justGetInCustomHeaderImage && self.justGetInCustomHeaderImage != nil && [[UserObj sharedInstance].headPicSrc rangeOfString:@"http://"].location != NSNotFound ) { //没有更改自定义头像
            [self startSubmitWithHeadPicSrc:[UserObj sharedInstance].headPicSrc];
        }else{  //更改了自定义头像。
            UpYun *uy = [[UpYun alloc] init];
            [kApp displayWaitViewWithAllMaskView:YES];
            [uy uploadFile:self.headPicImageView.image saveKey:[self getSaveKey]];
            uy.successBlocker = ^(id data){
                [kApp hideWaitView];
                NSString *headPicSrc = [NSString stringWithFormat:@"%@%@",UPYunBase,[data objectForKey:@"url"]];
                [self startSubmitWithHeadPicSrc:headPicSrc];
            };
            uy.failBlocker = ^(NSError * error){
                [kApp hideWaitView];
                [PopTips tipsAtTop:self.view Msg:NotifyUploadHeadFailed];
            };
        }
       
    }else{  //非自定义
        NSString *headPicSrc = [[self.headerArray objectAtIndex:self.selectedHeaderIndex] objectForKey:@"pic"];
        [self startSubmitWithHeadPicSrc:headPicSrc];
    }
}

-(NSString * )getSaveKey {
    return [NSString stringWithFormat:@"/%@/iOS/%.0f.png",AppleAppID,[[NSDate date] timeIntervalSince1970]];
}

-(void)startSubmitWithHeadPicSrc:(NSString *)headPicSrc{
    NSString *url = [NSString stringWithFormat:@"%@editUserInfo",API_BASE];
    UserObj *obj =[UserObj sharedInstance];
    NSString *userName = self.userNameLabel.text;
    NSString *headPicType = [NSString stringWithFormat:@"%d",(self.selectedHeaderIndex == 0 ? 2 : 1)];
    NSString *headPicId = (self.selectedHeaderIndex == 0 ? @"-1" : [[self.headerArray objectAtIndex:self.selectedHeaderIndex] objectForKey:@"id"]);
    NSString *campId = [[self.campArray objectAtIndex:self.selectedCampIndex] objectForKey:@"id"];
    
    NSString *hpic = nil;
    if (self.selectedHeaderIndex == 0) { //本地上传,给后台地址
        hpic = headPicSrc;
    }else{  //默认头像，给后台id。
        hpic = headPicId;
    }
    
    NSDictionary *dic = @{@"uid": obj.uid, @"accesskey":obj.accessKey,@"uname":userName, @"htype":headPicType, @"hpic":hpic,@"cid":campId};
    [kApp displayWaitViewWithAllMaskView:NO];
    [[AFGetData sharedInstance] startPost:url andInfo:dic andDataBodyBlock:^(id<AFMultipartFormData> formData) {
        
    } andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        [kApp hideWaitView];
        if (isSuccess) {
            NSDictionary *dic = responseObj;
            int flag = [[dic objectForKey:@"flag"] intValue];
            if (1 == flag) {
                obj.username = userName;
                obj.headId = headPicId;
                obj.headPicSrc = headPicSrc;
                obj.campId = campId;
                obj.isLogin = YES;
                [obj saveUserToLocal];
                [PopTips tipsAtTop:kApp.rootNav.view Msg:NotifyUserInfoEditSuccess];
                [self.navigationController popToViewController:kApp.meHomeVC animated:YES];
            }else if(3 == flag){
                [PopTips tipsAtTop:self.view Msg:NotifyUserNameHasExist];
            }else{
                [PopTips tipsAtTop:self.view Msg:NotifyUserInfoEditFailed];
            }
        }else{
            [[kHandle sharedInstance] showTipsWhenRequestFailedWithView:self.view];
        }
        
    }];
}


- (IBAction)changeUserName:(id)sender {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NotifyChangeNameAlertTitle
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"确定", nil];
    alertView.tag = AlertViewChangeNameTag;
    [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [alertView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == AlertViewChangeNameTag) {
        if (buttonIndex == 1) {
            NSString *name = [alertView textFieldAtIndex:0].text;
            if ([Common removeCharacterSpace:name].length < 2) {
                [PopTips tipsAtMiddle:self.view Msg:NotifyUserNameValid];
                [self changeUserName:nil];
            }else {
                self.userNameLabel.text = name;
            }
        }
    }
}

- (IBAction)goBack:(id)sender {
    if (self.firstRegisterToGoTo) {
        UserObj *obj =[UserObj sharedInstance];
        obj.isLogin = YES;
        [obj saveUserToLocal];
        [PopTips tipsAtTop:self.view Msg:NotifyLoginSuccess];
        [self.navigationController popToViewController:kApp.meHomeVC animated:YES];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    UIImagePickerController *controller = nil;
    if (buttonIndex == 0) {
        controller = [CameraAndPhoto getCameraPickerControllerAndIsFront:YES];
        if (controller) {
            controller.delegate = self;
            [self presentViewController:controller animated:YES completion:nil];
        }else{
           [PopTips tipsAtTop:self.view Msg:NotifyGetCameraFailed];
        }
        
    } else if (buttonIndex == 1) {
        controller = [CameraAndPhoto getPhotoLibarayPickerController];
        if (controller) {
            controller.delegate = self;
            [self presentViewController:controller animated:YES completion:nil];
        }else{
           [PopTips tipsAtTop:self.view Msg:NotifyGetPhotoLibFailed];
        }
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [CameraAndPhoto imageByScalingToMaxSize:portraitImg andMaxWidth:400];
        
        // present the cropper view controller
        VPImageCropperViewController *imgCropperVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, (isiPhone5 ? 100 : 40), self.view.width, self.view.width) limitScaleRatio:3.0];
        imgCropperVC.delegate = self;
        [self presentViewController:imgCropperVC animated:YES completion:nil];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark - VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    // TODO Profile image is Crop image
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        self.headPicImageView.image = editedImage;
        self.selectedHeaderIndex = 0;
        [self.headerCollectView reloadData];
    }];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:nil];
}


#pragma -mark collectionView
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section
{
    if (view == self.headerCollectView) {
        return self.headerArray.count;
    }else{
        return self.campArray.count;
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier =CellIdentifer;
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    
    UILabel *titleLabel=(UILabel *)[cell viewWithTag:200];
    UIView *shadowView = [cell viewWithTag:205];
    UIButton *clickedBtn=(UIButton *)[cell viewWithTag:201];
    UIImageView *trueImageView = (UIImageView *)[cell viewWithTag:302];
    
    NSDictionary *dic = nil;
    if (collectionView == self.headerCollectView) {
        shadowView.hidden = YES;
        titleLabel.hidden = YES;
        dic = [self.headerArray objectAtIndex:indexPath.row];
        
        clickedBtn.titleLabel.text = [NSString stringWithFormat:@"header_%d",(int)indexPath.row];
        if (indexPath.row == self.selectedHeaderIndex && self.selectedHeaderIndex !=0 ) {
            clickedBtn.selected = YES;
        }else{
            clickedBtn.selected = NO;
        }
        
    }else{
        trueImageView.backgroundColor = [UIColor whiteColor];
        dic = [self.campArray objectAtIndex:indexPath.row];
        clickedBtn.titleLabel.text = [NSString stringWithFormat:@"camp_%d",(int)indexPath.row];
        if (indexPath.row == self.selectedCampIndex) {
            clickedBtn.selected = YES;
        }else{
            clickedBtn.selected = NO;
        }
        titleLabel.text = [dic objectForKey:@"title"];
        
    }
    
    [clickedBtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [[AFGetData sharedInstance] initSDWebImage:[dic objectForKey:@"pic"] andTrueImageView:trueImageView andPlaceholderImage:nil];
    
    return cell;
    
   
}
-(void)btnClicked:(id)sender{
    UIButton *btn = (UIButton *)sender;
    if (btn.selected) {
        return;
    }
    NSString *string = btn.titleLabel.text;
    NSArray *tempArray = [string componentsSeparatedByString:@"_"];
    int index = [[tempArray objectAtIndex:1] intValue];
    if ([[tempArray objectAtIndex:0] isEqualToString:@"header"]) {
        if (index == 0) {
            UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                                     delegate:self
                                                            cancelButtonTitle:@"取消"
                                                       destructiveButtonTitle:nil
                                                            otherButtonTitles:@"拍照", @"从相册中选取", nil];
            [choiceSheet showInView:self.view];
        }else{
            self.selectedHeaderIndex = index;
            [[AFGetData sharedInstance] initSDWebImage:[[self.headerArray objectAtIndex:index] objectForKey:@"pic"] andTrueImageView:self.headPicImageView andPlaceholderImage:nil];
           [self.headerCollectView reloadData];
        }
        
    }else{
        self.selectedCampIndex = index;
        [self.campCollectView reloadData];
    }
}

-(UICollectionView*)drawCollectionViewWithFrame:(CGRect)frame andFlowLayout:(UICollectionViewFlowLayout*)flowLayout
{
    UICollectionView* myCollectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:flowLayout];
    myCollectionView.showsVerticalScrollIndicator = NO;
    myCollectionView.showsHorizontalScrollIndicator = NO;
    myCollectionView.dataSource = self;
    myCollectionView.delegate = self;
    myCollectionView.backgroundColor = [UIColor clearColor];
    return myCollectionView;
}

-(UICollectionViewFlowLayout*)getFlowLayout
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setItemSize:CGSizeMake(81, 76)];
    flowLayout.minimumInteritemSpacing =1;
    flowLayout.minimumLineSpacing =1;
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);  //top left bottom right
    return flowLayout;
}

-(void)registerCellAndHeaderForCollectionView:(UICollectionView*)collectionView
{
    UINib *cellNib = [UINib nibWithNibName:@"PersonalInfoCollectionCell" bundle:nil];
    [collectionView registerNib:cellNib forCellWithReuseIdentifier:CellIdentifer];
    
}

@end
